package com.atguigu.exam.service.impl;

import com.atguigu.exam.config.properties.MinioProperties;
import com.atguigu.exam.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * projectName: com.atguigu.exam.service.impl
 *
 * @author: 赵伟风
 * description:
 */
@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;
    /**
     * 上传文件（自动选择MinIO或本地存储）
     * @param file 上传的文件
     * @param folder 文件夹名称（如：banners, avatars等）
     * @return 返回图片可访问地址
     */
    @Override
    public String uploadFile(MultipartFile file, String folder) throws Exception{
        //判断桶是否存在
        boolean flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        if (!flag){
            log.info("创建bucket并设置成public权限");
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            log.info("bucket创建成功");
        }
        else{
            log.info("bucket已存在");
        }
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //对当前日期进行格式化
        String format = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
        //生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //创建新的文件名
        String fileName = format + "/" + uuid + suffix;



        //设置输入流
        InputStream inputStream = file.getInputStream();
        //创建PutObjectArgs对象
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                //桶的名字
                .bucket(minioProperties.getBucketName())
                //设置上传文件的名字
                .object(fileName)
                //设置上传文件的输入流
                .stream(file.getInputStream(), file.getSize(), -1)
                .build();
        log.info("开始上传文件");
        minioClient.putObject(putObjectArgs);
        log.info("上传文件成功");
        //返回路径
        return minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+fileName;
    }
}
